package com.commerce.img.tools;

import android.app.DownloadManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.widget.Toast;

public class MyLoadImg {
    public void getImage(Context context,String url,String desc){
        //下载服务
        DownloadManager downloadM = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        //下载请求
        DownloadManager.Request down = new DownloadManager.Request(Uri.parse(url));
        //下载标题
        down.setTitle(desc);
        down.setDescription("这是一个图片");
        //下载支持方式2G/3G/4G和wifi
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        //通知方式
        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);
        //存入地址
        down.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS+"/img",desc+".png");
        //服务放入请求
        //通过getSystemService()方法得到connectionManager这个系统服务类，专门用于管理网络连接
        ConnectivityManager connectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //判断网络
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            downloadM.enqueue(down);
        } else {
            Toast.makeText(context, "网络不可用", Toast.LENGTH_SHORT).show();
        }
        }else {
            downloadM.enqueue(down);
        }
    }
}
